<template>
  <!-- 每日对账 -->
  <zsearch>
      <template #title>
        <span>收费日期</span>
      </template>
      <template #date>
        <el-date-picker
          v-model="dayString"
          type="date"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD"
          >
        </el-date-picker>

        <!-- <el-date-picker
          v-model="endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          >
        </el-date-picker> -->
      </template>
      <template #select>
        <el-radio-group v-model="byUserType">
          <el-radio :label="'医生'">医生</el-radio>
          <el-radio :label="'收银员'">收银员</el-radio>
          <el-radio :label="'咨询师'">咨询师</el-radio>
        </el-radio-group>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch">查询</el-button>
			  <el-button class="btn-2">导出</el-button>
      </template>
      <template #table>
        <div class="table-content" v-loading="loading">
          <el-table
          :data="tableData"
          style="width: 100%"
          height='100%'
          show-summary
          :summary-method="hanledAdd"
          default-expand-all
          >
            <el-table-column width="150">
              <template #default="props">
              <span>{{byUserType}}</span>: {{props.row.userName}}
              </template>
            </el-table-column>
            <el-table-column type="expand">
              <template #default="props">
                <el-table 
                  :data="props.row.list" 
                  :show-header="false" 
                  show-summary
                  :summary-method="handleAddItem"
                  >
                <el-table-column width="178">
                </el-table-column>
                <el-table-column
                  v-for="i in columns"
                  :prop="i.name"
                  :label="i.show"
                  :width="i.width"
                  :align="i.name === 'status' ? 'left' : 'center'"
                  >
                </el-table-column>
                </el-table>
              </template>
            </el-table-column>
          
            <el-table-column
              v-for="i in columns"
              :prop="i.name"
              :label="i.show"
              :width="i.width"
              align="left"
              >
            </el-table-column>
          </el-table>
        </div>
      </template>
    </zsearch>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, ref, onMounted, watch } from '@vue/runtime-core'

import useRequet, { RespData } from "../../hook/network"

import useConfgin from '../../hook/getconfig'
import { getNowDates } from '../../utils/nowDate'

import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'

import { ElMessage } from 'element-plus'

type ColumnType = {
  name: string,
  show: string
  width?: number
}
// const ID = 501
export default defineComponent({
  name: 'DailyReconciliation',
  components: {
    ztable,
    zpage,
    zsearch
  },
  setup() {
    let search = reactive({
      dayString: `${getNowDates()}`,
      byUserType: '收银员'
    })
    watch(() => search.dayString,(newStartTime) => {
      console.log(newStartTime)
    })
    watch(() => search.byUserType, (newType) => {
      console.log(newType)
      req()
    })
    const loading = ref(false)
    const tableData = ref([])
    const columns = ref<ColumnType[]>([])

    const request = useRequet({ path: "" });
    const columnsWidth = {
      '患者姓名': 150,
      '收费时间': 220,
      '医生': 100,
      '就诊时间': 200,
      '欠费变动': 120,
      '口碑': 80,
      '收款人': 100,
      '应付': 120,
      '实收': 120,
      '银行卡': 120,
      '微信': 120,
      '省医保': 120,
      '微信付款': 120,
      '美团': 120,
      '市医保': 120,
      '支付宝': 120,
    }
    // 处理小数相加问题
    const speed = 10000000000;
    const req = () => {
      loading.value = true
      request.sendRequest({
        address: 'statistical/pay/dailyCheck',
        params: search,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          console.log(resp.data)
          if(resp.data) {
            tableData.value = resp.data.data || []
            columns.value = resp.data.title || []
            columns.value.forEach((item:any) => {
              console.log(item)
              item.width = columnsWidth[item.show] || ''
            })

            console.log(columns.value)
          }
          loading.value = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          console.log(resp, '错误')
        },
        method: "POST",
      })
      loading.value = false
    }
    onMounted(() => {
      req()
    })
    //搜索
    const hanledSearch = () => {
      req()
    }

    const hanledAdd = (param:any) => {
      const { columns, data } = param
      let datasList = <any>[]
      data.forEach((i:any) => {
        i.list.forEach((item: any) => {
          item.remark = ''
          datasList.push(item)
        })
      })
      const sums = <string[]>[]
      columns.forEach((column:any, index:number) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = datasList.map((item: any) => {
          if(item[column.property] !== '') {
            return Number(item[column.property])
          }
          
        })

        if (!values.every((value: any) => isNaN(value))) {
          sums[index] = `￥${values.reduce((prev:number, curr: number) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return ((prev * speed) + (curr * speed )) / speed
            } else {
              return Number(prev).toFixed(2)
            }
          }, 0)}`
        } else {
          sums[index] = ''
        }
      })
      return sums
    }

    const handleAddItem = (param:any) => {
      console.log(param)
      const { columns, data } = param
      const sums = <string[]>[]
      columns.forEach((column:any, index:number) => {
        if (index === 0) {
          sums[index] = '小计'
          return
        }
        const values = data.map((item: any) => {
          if(item[column.property] !== '') {
            return Number(item[column.property])
          }
          
        })

        if (!values.every((value: any) => isNaN(value))) {
          sums[index] = `￥${values.reduce((prev:number, curr: number) => {
            // console.log(prev, curr)
            const value = Number(curr)
            if (!isNaN(value)) {
              let nums = ((prev * speed) + (curr * speed )) / speed
              // console.log(nums.toFixed(2), 'nums')
              return nums
            } else {
              return Number(prev).toFixed(2)
            }
          }, 0)}`
        } else {
          sums[index] = ''
        }
      })
      console.log(sums)
      return sums
    }


    return {
      loading,
      tableData,
      columns,
      ...toRefs(search),
      hanledSearch,
      hanledAdd,
      handleAddItem

    }
  }
})
</script>

<style scoped lang="scss">
.table-content {
  height: 100%;
}
.tables {
  width: 100%;
}
th,td {
  padding: 10px 15px;
}


.el-table__row .expanded {
  border: 0;
}

</style>